/**
 * 
 */
package com.ws.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.ws.bean.Content;
import com.ws.bean.Message;
import com.ws.bean.User;


/**
 * @author zhong
 *
 */
@ServerEndpoint(value="/echo")
public class ChatSocket {
	
	private static String user = null;
	private static List<Session> sessions = new ArrayList<Session>();
	private static List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
	private static Map<String, Session> map = new HashMap<String, Session>();
	
	public ChatSocket(){
		
	}
	
	
	@OnOpen
	public void open(Session session){
		
		user = getSessionUser(session);
		
		Session ms = map.get(user);
		if(ms == null){
			map.put(user, session);
			sessions.add(session);
			
			User u = new User();
			u.setGroup("myfriend");
			u.setNickname(user);
			u.setSignature("我就是我,大名叫"+user+"的我~");

			userList.add(getUserMap(u));
		
			Message message = new Message();
			message.setType("online");
			message.setUsers(userList);
			message.setFrom(user);

			broadcast(sessions,JSON.toJSONString(message));

			System.out.println("===== 欢迎 "+user+" 进入IM, 当前共 "+userList.size() +" 人在线!");
		}
	}
	
	
	/**
	 * 消息广播
	 * @param sessions
	 * @param json
	 */
	private void broadcast(List<Session> sessions, String msg) {
		for(Iterator<Session> iterator = sessions.iterator(); iterator.hasNext();){
			Session session = (Session) iterator.next();
			try {
				if(session != null){
					session.getBasicRemote().sendText(msg);
				}else{
					System.out.println("======> broadcast session is NUll. by "+user);
				}
			} catch (IOException e) {
				System.out.println("=======> broadcast:"+user+" 已退出");
				e.printStackTrace();
			}
		}
	}


	@OnClose
	public void close(Session session){
		
		user = getSessionUser(session);
		sessions.remove(session);
		
		if(userList != null && userList.size() > 0){
			for (int i=0; i<userList.size(); i++) {
				Map<String, Object> map = userList.get(i);
				if(map.get(user) != null){
					userList.remove(map);
				}
				
			}
		}
		
		map.remove(user);
		Message message = new Message();
		message.setType("offline");
		message.setUsers(userList);
		System.out.println("======> "+user +" 已离线, 当前在线共 "+userList.size() +" 人!");
		

		broadcast(sessions,JSON.toJSONString(message));
	}
	
	
	/**
	 * 消息响应方法
	 * @param session
	 * @param json
	 */
	@OnMessage
	public void message(Session session,String json){
	
		String fromUser = getSessionUser(session);
		String toUser = null;
		
		Content content = (Content) JSON.parseArray(json, Content.class);
		if(content == null){
			return;
		}
		System.out.println("===== message:"+content.getMsg());
		
		//null 或 single
		if(content.getMode() == null){
			String to = content.getTo();
			if(to != null && to != ""){
				String toArr[] = to.split(","); 
				if(toArr == null || toArr.length == 0 ){
					return;
				}
				
				for(int i=0; i<toArr.length; i++){
					Session toSession = map.get(toArr[i]);
					
					if(toSession == null){
						continue;
					}
					
					toUser = getSessionUser(toSession);
					
					try {
						Message message = new Message();
						message.setType("message");
						message.setFrom(fromUser);
						message.setTo(toUser);
						message.setLayer(content.getLayer());
						message.setContent(content.getMsg());
						toSession.getBasicRemote().sendText(JSON.toJSONString(message));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else if(("model").equalsIgnoreCase(content.getMode())){
			Message message = new Message();
			message.setLayer(content.getLayer());
			message.setFrom(user);
			message.setType("message");
			message.setContent(content.getMsg());
			broadcast(sessions, JSON.toJSONString(message));
		}
		
	}
	
	
	
	/**
	 * 获取用户map
	 * @author zhong
	 * @param u
	 * @return
	 */
	public static Map<String, Object> getUserMap(User u){
		Map<String, Object> umap = null;
		if(u != null){
			umap = new HashMap<String, Object>();
			umap.put(user, JSON.toJSONString(u));
		}
		return umap;
	}
	
	
	/**
	 * 获取session用户
	 * @author zhong
	 * @param session
	 * @return
	 */
	public static String getSessionUser(Session session){
		String result = null;
		if(session != null){
			String parms = session.getQueryString();
			String[] parmArr = parms.split("=");
			if(parmArr != null && parmArr.length > 1){
				result = parmArr[1];
			}
		}
		return result;
		
	}
	
}
